package com.wing.sell.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.purchase.model.entity.SupplierDueSubjectCategory;
import com.wing.sell.dao.CustomerCategoryDao;
import com.wing.sell.model.entity.CustomerCategory;
import com.wing.sell.model.request.CustomerCategoryForm;
import com.wing.sell.model.response.CustomerCategoryVO;
import com.wing.sell.model.response.NodeDataVO;
import com.wing.sell.service.CustomerCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客户类别-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class CustomerCategoryServiceImpl extends ServiceImpl<CustomerCategoryDao, CustomerCategory> implements CustomerCategoryService {
    private static long ROOT_ID=-1l;
    @Override
    public int add(CustomerCategoryForm customerCategoryForm) {
        //校验
        CustomerCategory customerCategory =new CustomerCategory();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(CustomerCategory.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(customerCategoryForm, customerCategory, copyOptions);
        if (customerCategoryForm.getParentId()!=ROOT_ID){
            CustomerCategory customerCategoryParent = new CustomerCategory();
            customerCategoryParent.setId(customerCategoryForm.getParentId());
            customerCategoryParent.setHasChild(true);
            if (customerCategoryForm.getIsDeleted()){
                customerCategoryParent.setHasEnableChild(true);
            }
            baseMapper.updateById(customerCategoryParent);
        }
        return baseMapper.insert(customerCategory);
    }

    @Override
    public List<CustomerCategoryVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<CustomerCategoryVO> pageList4app(Page page, Map<String, Object> params) {
        List<CustomerCategoryVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public CustomerCategoryVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    @Transactional
    public int update(CustomerCategoryForm customerCategoryForm) {
        CustomerCategoryVO customerCategoryVO = baseMapper.get4appById(customerCategoryForm.getId());
        if (customerCategoryVO!=null){
            if (!customerCategoryVO.getParentId().equals(customerCategoryForm.getParentId())){
                CustomerCategory customerCategory = new CustomerCategory();
                BeanUtils.copyProperties(customerCategoryForm,customerCategory);
                baseMapper.updateById(customerCategory);

                if (customerCategoryForm.getParentId()!=ROOT_ID){
                    CustomerCategory parentCustomerCategory = new CustomerCategory();
                    parentCustomerCategory.setId(customerCategoryForm.getParentId());
                    parentCustomerCategory.setHasChild(true);
                    if (customerCategoryForm.getIsDeleted()){
                        parentCustomerCategory.setHasEnableChild(true);
                    }
                    baseMapper.updateById(parentCustomerCategory);
                }
                if (customerCategoryVO.getParentId()!=ROOT_ID){
                    int count = baseMapper.selectCount(new QueryWrapper<CustomerCategory>().eq("parent_id",customerCategoryVO.getParentId()));
                    if (count==0){
                        CustomerCategory customerCategoryParent = new CustomerCategory();
                        customerCategoryParent.setId(customerCategoryVO.getParentId());
                        customerCategoryParent.setHasChild(false);
                        baseMapper.updateById(customerCategoryParent);
                    }
                    count = baseMapper.selectCount(new QueryWrapper<CustomerCategory>().eq("parent_id",customerCategoryVO.getParentId()).eq("is_deleted",true));
                    if (count==0){
                        CustomerCategory customerCategoryParent = new CustomerCategory();
                        customerCategoryParent.setId(customerCategoryVO.getParentId());
                        customerCategoryParent.setHasChild(false);
                        baseMapper.updateById(customerCategoryParent);
                    }
                }
            }else{
                boolean isUpdateEnable=customerCategoryVO.getIsDeleted().equals(customerCategoryForm.getIsDeleted());
                CustomerCategory customerCategory = new CustomerCategory();
                BeanUtils.copyProperties(customerCategoryForm,customerCategory);
                baseMapper.updateById(customerCategory);
                if(isUpdateEnable&&!customerCategoryForm.getIsDeleted()&&customerCategoryForm.getParentId()!=ROOT_ID){
                    int count = baseMapper.selectCount(new QueryWrapper<CustomerCategory>().eq("parent_id",customerCategoryVO.getParentId()).eq("is_deleted",true));
                    if (count==0){
                        CustomerCategory customerCategoryParent = new CustomerCategory();
                        customerCategoryParent.setId(customerCategoryVO.getParentId());
                        customerCategoryParent.setHasChild(false);
                        baseMapper.updateById(customerCategoryParent);
                    }
                }
            }
        }
        return 0;
    }

    @Override
    @Transactional
    public int enable(Long id) {
        CustomerCategoryVO customerCategoryVO = baseMapper.get4appById(id);
        if(customerCategoryVO!=null){
            CustomerCategory customerCategory = new CustomerCategory();
            customerCategory.setId(id);
            customerCategory.setIsDeleted(true);
            int updateCount=baseMapper.updateById(customerCategory);
            if (customerCategoryVO.getParentId()!=ROOT_ID){
                CustomerCategory customerCategoryParent = new CustomerCategory();
                customerCategoryParent.setId(customerCategoryVO.getParentId());
                customerCategoryParent.setHasEnableChild(true);
                baseMapper.updateById(customerCategoryParent);
            }
            return updateCount;
        }
        return 0;
    }

    @Override
    public int disable(Long id) {
        CustomerCategoryVO customerCategoryVO = baseMapper.get4appById(id);
        if(customerCategoryVO!=null){
            CustomerCategory customerCategory = new CustomerCategory();
            customerCategory.setId(id);
            customerCategory.setIsDeleted(false);
            int updateCount=baseMapper.updateById(customerCategory);
            if (customerCategoryVO.getParentId()!=ROOT_ID){
                int count = baseMapper.selectCount(new QueryWrapper<CustomerCategory>().eq("parent_id",customerCategoryVO.getParentId()).eq("is_deleted",true));
                if(count==0){
                    CustomerCategory customerCategoryParent = new CustomerCategory();
                    customerCategoryParent.setId(customerCategoryVO.getParentId());
                    customerCategoryParent.setHasEnableChild(false);
                    baseMapper.updateById(customerCategoryParent);
                }
            }
            return updateCount;
        }
        return 0;
    }

    @Override
    public JsonResult getTreeData() {
        List<CustomerCategoryVO> list = baseMapper.list4app(new HashMap<>());
        Map<Long,List<NodeDataVO>> map=new HashMap<>();
        for (CustomerCategoryVO typeVO:list){
            if(map.containsKey(typeVO.getParentId())){
                NodeDataVO nodeDataVO=new NodeDataVO();
                nodeDataVO.setValue(typeVO.getId().toString());
                nodeDataVO.setName(typeVO.getName());
                map.get(typeVO.getParentId()).add(nodeDataVO);
            }else{
                List<NodeDataVO> tmpList=new ArrayList<>();
                NodeDataVO nodeDataVO=new NodeDataVO();
                nodeDataVO.setValue(typeVO.getId().toString());
                nodeDataVO.setName(typeVO.getName());
                tmpList.add(nodeDataVO);
                map.put(typeVO.getParentId(),tmpList);
            }
        }
        List<NodeDataVO> rootList=map.get(-1L);
        if (rootList==null){
            return JsonResult.success();
        }
        constructTree(rootList,map);
        return JsonResult.success(rootList);
    }

    @Override
    public boolean delete(Long customerCategoryId) {
        // 查询当前删除分类是否存在子类
        int count = baseMapper.selectCount(new QueryWrapper<CustomerCategory>().eq("parent_id", customerCategoryId));
        if(count > 0){
            throw new BusinessException(500, "请先删除子分类");
        }
        return removeById(customerCategoryId);
    }

    private void  constructTree(List<NodeDataVO> parentList, Map<Long,List<NodeDataVO>> dataMap){
        for (NodeDataVO node:parentList) {
            Long nodeId=Long.valueOf(node.getValue());
            List<NodeDataVO> childList=dataMap.get(nodeId);
            if (childList!=null){
                node.setChildren(childList);
                constructTree(childList,dataMap);
            }
        }
    }

}
